package com.linetime.wechat.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Status;
import com.linetime.collection.CollectionUtil;
import com.linetime.core.utils.JacksonUtil;
import com.linetime.core.utils.StringUtil;
import com.linetime.wechat.constants.MenuAPI;
import com.linetime.wechat.constants.WechatAPI;
import com.linetime.wechat.entity.Menu;
import com.linetime.wechat.exception.WechatException;
import com.linetime.wechat.response.BaseResponse;
import com.linetime.wechat.response.CreateMenuResponse;
import com.linetime.wechat.response.GetMenuResponse;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 菜单相关的 helper
 *
 * @author: saz
 * @date 2018/10/11 22:02
 */
public class MenuHelper {

    /**
     * 创建菜单
     *
     * @param accessToken access token
     * @param menu        菜单信息
     * @return 微信返回的信息
     */
    public static CreateMenuResponse createMenu(String accessToken, Menu menu) {
        if (StringUtil.isBlank(accessToken)) {
            throw new WechatException("access token is empty");
        }
        if (null == menu || CollectionUtil.isEmpty(menu.getButton())) {
            throw new WechatException("menu info is empty");
        }
        String url = null;
        if (null == menu.getMenuMatchRule()) {
            // 创建普通菜单
            url = MenuAPI.MENU_CREATE_API.replace("ACCESS_TOKEN", accessToken);
        } else {
            // 创建个性化菜单
            url = MenuAPI.CONDITIONAL_MENU_CREATE_API.replace(WechatAPI.ACCESS_TOKEN, accessToken);
        }
        HttpResponse response = HttpRequest.post(url).body(JacksonUtil.toJson(menu)).execute();
        if (null == response) {
            throw new WechatException("Create menu failure,response from the wechat is empty");
        }
        if (!Objects.equals(response.getStatus(), Status.HTTP_OK)) {
            throw new WechatException("Create menu failure,the response status from wechat is {}", response.getStatus());
        }
        return JacksonUtil.toBean(response.body(), CreateMenuResponse.class);
    }

    /**
     * 获取菜单
     *
     * @param accessToken access token
     * @return 菜单信息
     */
    public static GetMenuResponse getMenu(String accessToken) {
        if (StringUtil.isBlank(accessToken)) {
            throw new WechatException("access token is empty");
        }
        String url = MenuAPI.MENU_GET_API.replace(WechatAPI.ACCESS_TOKEN, accessToken);
        HttpResponse response = HttpRequest.get(url).execute();
        if (null == response) {
            throw new WechatException("Get menu failure,response from the wechat is empty");
        }
        if (!Objects.equals(response.getStatus(), Status.HTTP_OK)) {
            throw new WechatException("Get menu failure,the response status from wechat is {}", response.getStatus());
        }
        return JacksonUtil.toBean(response.body(), GetMenuResponse.class);
    }

    /**
     * 删除菜单
     *
     * @param accessToken accessToken
     * @return 微信公众平台返回信息
     */
    public static BaseResponse deleteMenu(String accessToken) {
        if (StringUtil.isBlank(accessToken)) {
            throw new WechatException("access token is empty");
        }
        String url = MenuAPI.MENU_DELETE_API.replace(WechatAPI.ACCESS_TOKEN, accessToken);
        HttpResponse response = HttpRequest.get(url).execute();
        if (null == response) {
            throw new WechatException("Delete menu failure,response from the wechat is empty");
        }
        if (!Objects.equals(response.getStatus(), Status.HTTP_OK)) {
            throw new WechatException("Delete menu failure,the response status from wechat is {}", response.getStatus());
        }
        return JacksonUtil.toBean(response.body(), BaseResponse.class);
    }

    /**
     * 删除个性化菜单
     *
     * @param accessToken accessToken
     * @param menuId      个性化菜单的Id
     * @return 微信公众平台返回信息
     */
    public static BaseResponse deleteConditionalMenu(String accessToken, String menuId) {
        if (StringUtil.isBlank(accessToken)) {
            throw new WechatException("access token is empty");
        }
        String url = MenuAPI.CONDITIONAL_MENU_DELETE_API.replace(WechatAPI.ACCESS_TOKEN, accessToken);
        Map<String, String> params = new HashMap<String, String>(1);
        params.put("menuid", menuId);
        HttpResponse response = HttpRequest.post(url).body(JacksonUtil.toJson(params)).execute();
        if (null == response) {
            throw new WechatException("Delete menu failure,response from the wechat is empty");
        }
        if (!Objects.equals(response.getStatus(), Status.HTTP_OK)) {
            throw new WechatException("Delete menu failure,the response status from wechat is {}", response.getStatus());
        }
        return JacksonUtil.toBean(response.body(), BaseResponse.class);
    }


    /**
     * 测试个性化菜单匹配
     *
     * @param accessToken accessToken
     * @param userId      user_id可以是粉丝的OpenID，也可以是粉丝的微信号。
     * @return 匹配的菜单信息
     */
    public static GetMenuResponse matchConditionalMenu(String accessToken, String userId) {
        if (StringUtils.isBlank(accessToken)) {
            throw new WechatException("access token is empty");
        }
        String url = MenuAPI.CONDITIONAL_MENU_MATCH_API.replace(WechatAPI.ACCESS_TOKEN, accessToken);
        Map<String, String> params = new HashMap<String, String>(1);
        params.put("user_id", userId);
        HttpResponse response = HttpRequest.post(url).body(JacksonUtil.toJson(JacksonUtil.toJson(params))).execute();
        if (null == response) {
            throw new WechatException("Match conditional menu failure,response from the wechat is empty");
        }
        if (!Objects.equals(response.getStatus(), Status.HTTP_OK)) {
            throw new WechatException("Match conditional menu failure,the response status from wechat is {}", response.getStatus());
        }
        return JacksonUtil.toBean(response.body(), GetMenuResponse.class);
    }

}
